﻿using System.Text;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.DomTemplateBuilder.Element;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler
{
	/// <summary>
	/// 对上下文进行设置的Handler
	/// </summary>
	public class EvaluateContextHandler : PropertyElementHandler
    {
		protected override object GetParamObject ( object rootParamObject, object parentParamObject, ITemplateRenderContext context, Element.PropertyValueStyles valueStyles = PropertyValueStyles.NotSet )
		{
			var ele = this.Element as IContextElement;
			object paramObject = null;
			if ( valueStyles == PropertyValueStyles.NotSet )
			{
				valueStyles = ele.ValueStyle;
			}
			if ( valueStyles == PropertyValueStyles.None )
			{
				return null;
			}
			switch ( valueStyles )
			{
				case PropertyValueStyles.RootObject:
					paramObject = rootParamObject;
					break;

				case PropertyValueStyles.Context:
				case PropertyValueStyles.NotSet:
					paramObject = context;
					break;

				case PropertyValueStyles.Parent:
					paramObject = parentParamObject;
					break;
			}
			return paramObject;
		}

        public override void DoRender ( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
        {
            var result = new StringBuilder ( );
            base.DoRenderChildNodes ( result, rootParamObject, parentParamObject, context );
			var target = this.GetParamObject ( rootParamObject, parentParamObject, context );
			var value = this.GetConvertedValue ( result.ToString ( ) );
			target.SetValue ( this.GetPropertyName ( rootParamObject, parentParamObject, context ), value );
        }
    }
}
